package com.driving.exam.spider.parser;

import java.util.List;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import com.driving.exam.entity.Exercise;

import cn.guet.base.spider.IParser;
import cn.guet.base.spider.http.HttpClientUtil;

/**
 * 习题解析和图片
 *
 * @author SAGITTAR
 */
@Component(value = "drivingExamParser")
public class DrivingExamParser implements IParser<List<Exercise>, List<Exercise>> {

    private static final Logger LOGGER = LogManager.getLogger(DrivingExamParser.class);

    @Override
    public List<Exercise> parse(List<Exercise> source) {
        source.forEach(exercise -> {
            // 针对科目四，客车货车没有解析地址的情况
            if (exercise.getSubjectId() == 4 && StringUtils.isBlank(exercise.getExplanation())) {
                exercise.setExplanation(String.format("http://km4.jsyst.cn/fx/q%s/", exercise.getOrdinal()));
            }
            String url = HttpClientUtil.validUrl(exercise.getExplanation());
            try {
                Document html = Jsoup.parse(HttpClientUtil.getWebPage(url, "GBK"));
                if (StringUtils.isNotBlank(exercise.getPicture())) {
                    Elements tagImg = html.select("img[alt]");
                    if (Objects.nonNull(tagImg)) {
                        exercise.setPicture(tagImg.first().attr("src"));
                    }
                }
                Elements tagB = html.select("b");
                if (Objects.nonNull(tagB)) {
                    tagB.forEach(b -> {
                        if (StringUtils.contains(b.ownText(), "分析：")) {
                            exercise.setExplanation(StringUtils.substringBefore(b.parent().ownText(), "更多试题").trim());
                        }
                    });
                }
                LOGGER.warn(new JSONObject(exercise));
            } catch (Exception e) {
                LOGGER.error(exercise.getOrdinal() + " -> " + url, e);
            }
        });
        return source;
    }
}
